import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

// GET /api/expenses/[id] - 获取支出详情
export async function GET(request: NextRequest) {
  const id = request.nextUrl.pathname.split('/').pop();
  if (!id) {
    return NextResponse.json(
      { error: '无效的ID' },
      { status: 400 }
    );
  }

  try {
    const expense = await prisma.expense.findUnique({
      where: { id },
      include: {
        site: {
          select: {
            id: true,
            name: true,
          },
        },
      },
    });

    if (!expense) {
      return NextResponse.json(
        { error: '支出记录不存在' },
        { status: 404 }
      );
    }

    return NextResponse.json(expense);
  } catch (error) {
    console.error('获取支出详情失败:', error);
    return NextResponse.json(
      { error: '获取支出详情失败' },
      { status: 500 }
    );
  }
}

// PUT /api/expenses/[id] - 更新支出
export async function PUT(request: NextRequest) {
  const id = request.nextUrl.pathname.split('/').pop();
  if (!id) {
    return NextResponse.json(
      { error: '无效的ID' },
      { status: 400 }
    );
  }

  try {
    const data = await request.json();
    const expense = await prisma.expense.update({
      where: { id },
      data,
      include: {
        site: {
          select: {
            id: true,
            name: true,
          },
        },
      },
    });

    return NextResponse.json(expense);
  } catch (error) {
    console.error('更新支出失败:', error);
    if (error instanceof Error && error.message.includes('Record to update not found')) {
      return NextResponse.json(
        { error: '支出记录不存在' },
        { status: 404 }
      );
    }
    return NextResponse.json(
      { error: '更新支出失败' },
      { status: 500 }
    );
  }
}

// DELETE /api/expenses/[id] - 删除支出
export async function DELETE(request: NextRequest) {
  const id = request.nextUrl.pathname.split('/').pop();
  if (!id) {
    return NextResponse.json(
      { error: '无效的ID' },
      { status: 400 }
    );
  }

  try {
    const expense = await prisma.expense.delete({
      where: { id }
    });

    return NextResponse.json(expense);
  } catch (error) {
    console.error('删除支出失败:', error);
    if (error instanceof Error && error.message.includes('Record to delete does not exist')) {
      return NextResponse.json(
        { error: '支出记录不存在' },
        { status: 404 }
      );
    }
    return NextResponse.json(
      { error: '删除支出失败' },
      { status: 500 }
    );
  }
}